<template>
  <div class="upload-file">
    <el-upload multiple :action="url" :before-upload="handleBeforeUpload" :file-list="fileList"
      :on-change="handleChange" :on-error="handleUploadError" :on-exceed="handleExceed"
      :on-success="handleUploadSuccess" :show-file-list="false" :headers="headers" class="upload-file-uploader" :on-progress="uploadProgress"
      ref="upload" :auto-upload="true" style="display: inline-block" :disabled="disabled" :data="dataObj">
      <!-- 上传按钮 -->
      <el-button type="primary" plain v-if="!props.isShow">重新上传</el-button>
      <el-button type="primary" plain v-else>上传</el-button>
    </el-upload>
    <!-- 上传提示 -->
    <div class="el-upload__tip" v-if="props.showTip">
      请上传
      <template v-if="fileSize"> 大小不超过 <b style="color: #f56c6c">{{ fileSize }}MB</b> </template>
      <!--<template v-if="fileType"> 格式为 <b style="color: #f56c6c">{{ fileType.join("/") }}</b> </template>-->
      的文件
    </div>
    <!-- 文件列表 -->

    <!-- 上传进度展示 -->
    <el-dialog v-model="openUpload" title="正在上传报告" width="400px" :close-on-click-modal="false"  append-to-body :show-close="false">
      <p></p>
      <div class="demo-progress">
        <el-progress :percentage="percentage" />
      </div>
      <div class="footer">
        <el-button plain @click="cancelUpload">取消上传</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script setup>
import { getToken } from "@/utils/auth";
// import { uploadReport } from "@/api/resultManag/reportManger.js";

const props = defineProps({
  modelValue: [String, Object, Array],
  // 数量限制
  limit: {
    type: Number,
    default: 1,
  },
  // 大小限制(MB)
  fileSize: {
    type: Number,
    default: 100,
  },
  // 文件类型, 例如['png', 'jpg', 'jpeg']
  fileType: {
    type: Array,
    default: () => ["doc", "xls", "ppt", "txt", "pdf"],
    // default: () => [],
  },
  // 是否显示提示
  isShowTip: {
    type: Boolean,
    default: true
  },
  // 是否显示提示
  isShow: {
    type: Boolean,
    default: false
  },
  disabled: {
    type: Boolean,
  },
  uploadFileUrl: {
    type: String,
  },
  type: {
    type: String,
    default: '1',
  },
  taskId: {
    type: String,
    default: '1',
  },
});

const { proxy } = getCurrentInstance();
const emit = defineEmits();
const headers = ref({ token: "tokrn" + getToken() });
const fileList = ref([]);
const url = import.meta.env.VITE_APP_BASE_API + "/report/uploadReport";
const openUpload = ref(false);
const percentage = ref(0);
const showTip = computed(
  () => props.isShowTip && (props.fileType || props.fileSize)
);
const dataObj = computed(() => {
  if (props.taskId) {
    return {
      type: '1',
      taskId: props.taskId,
      level: '1',
    }
  }
})

// 上传前校检格式和大小
function handleBeforeUpload(file) {
  // 校检文件类型
  if (props.fileType.length) {
    let fileExtension = "";
    if (file.name.lastIndexOf(".") > -1) {
      fileExtension = file.name.slice(file.name.lastIndexOf(".") + 1);
    }
    const isTypeOk = props.fileType.some((type) => {
      if (file.type.indexOf(type) > -1) return true;
      if (fileExtension && fileExtension.indexOf(type) > -1) return true;
      return false;
    });
    if (!isTypeOk) {
      proxy.$modal.msgError(`文件格式不正确, 请上传${props.fileType.join("/")}格式文件!`);
      return false;
    }
  }
  // 校检文件大小
  if (props.fileSize) {
    const isLt = file.size / 1024 / 1024 < props.fileSize;
    if (!isLt) {
      proxy.$modal.msgError(`上传文件大小不能超过 ${props.fileSize} MB!`);
      return false;
    }
  }
  openUpload.value = true;
}

function handleChange(file, fileList) {
  if (fileList.length > 1) {
    fileList.shift()
  }
}

// 文件个数超出
function handleExceed() {
  proxy.$modal.msgError(`上传文件数量不能超过 ${props.limit} 个!`);
}

// 上传失败
function handleUploadError(err) {
  proxy.$modal.msgError("上传文件失败");
  openUpload.value = false;
}

// 文件上传进度
function uploadProgress(event,file,fileList){
  if(event.lengthComputable){
    let val = (event.loaded / event.total * 100).toFixed(0);
    percentage.value = parseInt(val);
    console.log(percentage.value);
  }
}

// 上传成功回调
function handleUploadSuccess(res, file) {
  if (res.code != 200) {
    proxy.$modal.msgError("上传文件失败");
    openUpload.value = false;
  } else {
    proxy.$modal.msgSuccess("上传文件成功");
    openUpload.value = false;
    emit('uploadSuccess', { data: res.data, type: props.type })
  }
}

// 取消上传
function cancelUpload(){
  proxy.$refs["upload"].abort();
  openUpload.value = false;
}
defineExpose({
  fileList
});
</script>

<style scoped lang="scss">
.upload-file {
  width: 100%;
}

.upload-file-uploader {
  margin-bottom: 5px;
}

.upload-file-list .el-upload-list__item {
  border: 1px solid #e4e7ed;
  line-height: 2;
  margin-bottom: 10px;
  position: relative;
}

.upload-file-list .ele-upload-list__item-content {
  display: flex;
  justify-content: space-between;
  align-items: center;
  color: inherit;
}

.ele-upload-list__item-content-action .el-link {
  margin-right: 10px;
}

.demo-progress .el-progress--line {
  margin: 40px 0;
  // margin-bottom: 15px;
  width: 350px;
}
.footer{
  text-align: center;
}
</style>
